package entity

import (
	"code.gitea.io/gitea/modules/setting"
	"encoding/json"
	"net/http"
	"strings"
)

// ResultType 定义了响应格式
type ResultType struct {
	Code int         `json:"code"`
	Msg  string      `json:"msg"`
	Data interface{} `json:"data,omitempty"` // Data 字段可选
}

// RespondJson2HttpResponseWriter
// 将 ResultType 响应转换为 JSON 并写入响应
func (t *ResultType) RespondJson2HttpResponseWriter(w http.ResponseWriter) {
	responseBytes, err := json.Marshal(*t)
	if err != nil {
		// 只有序列化 ResultType 失败时候, 才返回 HTTP 500 Internal Server Error
		http.Error(w, http.StatusText(http.StatusInternalServerError)+": failed to marshal JSON", http.StatusInternalServerError)
		return
	}

	// 序列化 ResultType 成功，无论成功或者失败，统一返回 HTTP 200 OK
	if setting.CORSConfig.Enabled {
		AllowOrigin := setting.CORSConfig.AllowDomain[0]
		if AllowOrigin == "" {
			AllowOrigin = "*"
		}
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Access-Control-Allow-Origin", AllowOrigin)
		w.Header().Set("Access-Control-Allow-Methods", strings.Join(setting.CORSConfig.Methods, ","))
		w.Header().Set("Access-Control-Allow-Headers", strings.Join(setting.CORSConfig.Headers, ","))
	} else {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.Header().Set("Access-Control-Allow-Origin", "*")
		w.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE")
		w.Header().Set("Access-Control-Allow-Headers", "Accept, Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization")
	}
	w.WriteHeader(http.StatusOK)
	_, _ = w.Write(responseBytes)
}

// RespSuccess 操作成功常量
var RespSuccess = ResultType{
	Code: 0,
	Msg:  "操作成功",
}

// RespUnauthorizedFailure 获取 devContainer 信息失败：用户未授权
var RespUnauthorizedFailure = ResultType{
	Code: 00001,
	Msg:  "未登录，禁止访问",
}
